<?php
/**
 * Created by PhpStorm.
 * User: wxy
 * Date: 2018/11/8
 * Time: 17:08
 */

namespace frontend\modules\common\models;


use yii\base\Exception;
use yii\web\NotFoundHttpException;

class UploadExcel
{
    public $savePath;
    //允许上传的后缀
    protected $allowSuffix = ['xlsx', 'xls', 'csv'];

    protected $maxSize = 268435456;
    //文件后缀
    protected $suffix;
    //文件大小
    protected $size;

    public function __construct($savePath)
    {
        $this->savePath = $savePath;
    }

    /**
     * @param $file
     * @return string
     * @throws \yii\base\ExitException
     */
    public function Upload($file)
    {
        //设置脚本运行时间（单位：秒） 0-没有时间限制
        set_time_limit(0);
        //用来设置php.ini的值，在函数执行的时候生效，脚本结束后，设置失效
        //memory_limit-设定一个脚本所能够申请到的最大内存字节数
        ini_set('memory_limit', '256M');

        $code = $file['excel']['error'];
        if ($code > 0) {
            BaseHelper::Error($this->_errorCode($code));
        }
        $nameArr = explode(".", $file['excel']["name"]);
        $this->suffix = strtolower($nameArr[count($nameArr) - 1]);
        $this->size = $file['excel']['size'];
        //判断后缀
        if (!in_array($this->suffix, $this->allowSuffix)) {
            BaseHelper::Error('文件格式不正确');
        }
        if ($this->size > $this->maxSize) {
            BaseHelper::Error('文件超过上传限制');
        }
        //文件的临时副本的名称
        $tmp_name = $file['excel']['tmp_name'];

        $filename = date('YmdHis') . '.' . $this->suffix;
        //存储的路径
        $path = $this->savePath . $filename;
        //移动文件
        $res = move_uploaded_file($tmp_name, $path);
        if (!$res) {
            BaseHelper::Error('保存失败');
        }
        return $filename;
    }

    public function _errorCode($code)
    {

        switch ($code) {
            case 1:
                $msg = '超过php.ini upload_max_filesize限制';
                break;
            case 6:
                $msg = '找不到临时文件夹';
                break;
            default:
                $msg = '上传失败';
                break;
        }

        return $msg;
    }

}